﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.IO;

namespace MapEditorMario
{
    class QuadTree
    {
        #region variable

        private static int max_level;           //muc cua node
        QNode root;                             //Node goc

        public int sum_node;

        //2,4,8,16,32,64,128,256,512,1024,2048,4096,8192,16384
        int[] size_quadtree = { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384 };
        int max_size_node = 512;
        #endregion

        #region properties
        public QNode Root
        {
            get { return root; }
        }
        public int MaxLevel
        {
            get { return max_level; }
        }
        #endregion

        #region contructor
        public QuadTree(int pos_x, int pos_y, int size, int _level)
        {            
            max_level = _level;
            int temp_size = size;
            for (int i = 1; i < size_quadtree.Length; i++ )
            {
                if (size_quadtree[i-1] <= size && size <= size_quadtree[i])
                {
                    temp_size = size_quadtree[i];
                    break;
                }
            }
            root = new QNode(pos_x, pos_y, temp_size, 0, 0);

            sum_node = 0;
        }
        #endregion

        #region method
        public void addAllCTreeObject(string file_name)
        {
            FileStream fs = File.Open(file_name, FileMode.Open, FileAccess.Read);
            StreamReader sReader = new StreamReader(fs);
            int index_line = 0;
            while (!sReader.EndOfStream)
            {
                index_line++;
                string line = sReader.ReadLine();
                if (index_line == 1)    //dong dau tien k lay
                {
                }
                else
                {
                    string[] word_list = line.Split(' ');

                    GameObject obj_game = new GameObject(Convert.ToInt32(word_list[0]),
                                                         Convert.ToInt32(word_list[2]),
                                                         Convert.ToInt32(word_list[3]),
                                                         Convert.ToInt32(word_list[4]),
                                                         Convert.ToInt32(word_list[5]),
                                                         Convert.ToInt32(word_list[7]));
                    CTreeObject obj_tree = new CTreeObject((obj_game));

                    root.addCTreeObject(obj_tree);  //add object game vo node goc
                }
            }
            sReader.Close();
            fs.Close();
        }

        public void addAllTiles(string file_name)
        {
            FileStream fs = File.Open(file_name, FileMode.Open, FileAccess.Read);
            StreamReader sReader = new StreamReader(fs);
            int index_line = 0;

            List<int> tilesList = new List<int>();

            int iHeight = 0;
            int index = 1;
            while (!sReader.EndOfStream)
            {
                index_line++;
                string line = sReader.ReadLine();
                if (index_line == 1)    //dong dau tien k lay
                {
                }
                else
                {
                    string[] word_list = line.Split(' ');

                    for (int j = 0; j < word_list.Length; j++ )
                    {
                        int id_type = Convert.ToInt32(word_list[j]);
                        tilesList.Add(id_type);

                        GameObject obj_game = new GameObject(index++,
                                                             j*32,
                                                             iHeight*32,
                                                             j*32 + 32,
                                                             iHeight*32 + 32,
                                                             id_type);
                        CTreeObject obj_tree = new CTreeObject((obj_game));

                        root.addCTreeObject(obj_tree);  //add object game vo node goc

                        //index++;
                    }
                    iHeight++;
                }
            }
            sReader.Close();
            fs.Close();
        }

        public void divide()
        {
            build(this.root);

        }

        public void build(QNode n)
        {
            if (n.Size <= max_size_node)//256
            {
                return;
            }
            sum_node++;
            
            int size = n.Size / 2;

            n.LeftTop = new QNode(n.X1, n.Y1, size, n.Level + 1, n.IDNode * 10 + 1);
            n.RightTop = new QNode(n.X1 + size, n.Y1, size, n.Level + 1, n.IDNode * 10 + 2);
            n.LeftBottom = new QNode(n.X1, n.Y1 + size, size, n.Level + 1, n.IDNode * 10 + 3);
            n.RightBottom = new QNode(n.X1 + size, n.Y1 + size, size, n.Level + 1, n.IDNode * 10 + 4);

            for (int i = 0; i < n.ObjList.Count; i++)
            {
                clip(n.ObjList[i], n.LeftTop);
                clip(n.ObjList[i], n.RightTop);
                clip(n.ObjList[i], n.LeftBottom);
                clip(n.ObjList[i], n.RightBottom);
            }

            //xoa danh sach obj cua node goc
            n.ObjList.Clear();

            //build cac node con
            build(n.LeftTop);
            build(n.RightTop);
            build(n.LeftBottom);
            build(n.RightBottom);
        }

        public void clip(CTreeObject obj, QNode qNode)
        {
            //Xu ly clip
            bool is_clip = false;
            if (!(obj.X2 < qNode.X1 || obj.X1 > qNode.X2 || obj.Y2 < qNode.Y1 || obj.Y1 > qNode.Y2))
            {
                is_clip = true;
            }
            else
            {
                is_clip = false;
            }
            
            if (is_clip == true)
            {
                //rect obj giao voi rect qnode
                qNode.addCTreeObject(obj); //them obj vao list obj cua qnode
            }
        }

        public void saveQTree(string file_name)
        {
            FileStream fs = new FileStream(file_name, FileMode.Create); //tao file moi
            save(this.root, fs);
            fs.Close();
        }

        public void save(QNode n, FileStream fs)
        {
            StreamWriter sWriter = new StreamWriter(fs); //

            sWriter.Write(n.IDNode);
            sWriter.Write(" ");
            sWriter.Write(n.X1);
            sWriter.Write(" ");
            sWriter.Write(n.Y1);
            sWriter.Write(" ");
            sWriter.Write(n.X2);
            sWriter.Write(" ");
            sWriter.Write(n.Y2);

            for (int i = 0; i < n.ObjList.Count; i++ )
            {
                sWriter.Write(" ");
                sWriter.Write(n.ObjList[i].ObjID);
            }
            sWriter.WriteLine("");    //xuong dong
            

            //Ghi cac node con vao file
            if (n.LeftTop != null) save(n.LeftTop, fs);
            if (n.RightTop != null) save(n.RightTop, fs);
            if (n.LeftBottom != null) save(n.LeftBottom, fs);
            if (n.RightBottom != null) save(n.RightBottom, fs);

            sWriter.Flush();
        }


        #endregion
    }
}
